﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Business;
using Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;
using iTextSharp.text.xml;
using iTextSharp.text.html;
using DataAccess;
//using System.Windows.Forms;

public partial class client_oilReport : @base {
    Client client = new Client();
    PdfWriter writer;
    ArrayList title = new ArrayList(3);
    ArrayList infor = new ArrayList(16);
    Paragraph pa;
    PdfPTable tableInfo = new PdfPTable(2);
    bool changeSite = false, changeSeverity = false;
    DataTable severity = new DataTable();
    DataTable Sites = new DataTable();
    DataTable Clients = new DataTable();

    Client selectedClient = new Client();
    UserServices user = new UserServices();

    ReportServices report = new ReportServices();
    OilReportService or = new OilReportService();
    List<string> sourses = new List<string>();
    //string str_date = "";

    string component_id;

    int selectedClient_id;


    private class headerfooter {
        private PdfPTable head;
        private PdfPTable foot;
        private iTextSharp.text.Image _img;
        private iTextSharp.text.Font font;
        private String t1 = "i2iTechnologies PO Box 1192, Clevand Qld 4163, Australia";
        private String t2 = "Office (07) 3829 1235 Fax (07) 3829 1238 Mob: 0439 717 244 Web: www.i2i-technologies.com.au ";
        private String t3 = "@i2iTechnologies";

        public headerfooter() {
            head = new PdfPTable(1);
            foot = new PdfPTable(1);
            font = new iTextSharp.text.Font();
            font.Color = BaseColor.BLUE;
            font.Size = 6f;
            font.SetFamily("Arial");
        }
        public PdfPTable Head {
            get { return head; }

        }
        public PdfPTable Foot {
            get { return foot; }

        }

        public void setHeader(String path, float width, int align, int border, int scale) {
            PdfPTable header = new PdfPTable(1);
            header.TotalWidth = width - 35;
            _img = iTextSharp.text.Image.GetInstance(path);
            _img.ScalePercent(scale);
            PdfPCell c = new PdfPCell(_img, false);

            c.HorizontalAlignment = align;
            c.Border = border;
            header.AddCell(c);
            head = header;

        }
        public void setFooter(float width) {

            PdfPTable footer = new PdfPTable(1);
            footer.TotalWidth = width;
            Chunk ck = new Chunk(t1, font);
            Phrase p1 = new Phrase(ck);

            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_CENTER;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_MIDDLE;

            fc.Rowspan = 1;
            footer.AddCell(fc);

            ck = new Chunk(t2, font);
            fc.Phrase = new Phrase(ck);
            fc.Rowspan = 1;
            footer.AddCell(fc);

            fc.Rowspan = 1;

            ck = new Chunk(t3, font);
            fc.Phrase = new Phrase(ck);
            footer.AddCell(fc);

            foot = footer;

        }
    }

    private class _events : PdfPageEventHelper {
        // private iTextSharp.text.Image _img;
        private String path;



        public _events(String p) {
            /*
            * create single instance so image bytes added **ONCE** to the PDF file,
            * instead of every time you start a new page
            */

            path = p + "/logo.png";
            //     _img = iTextSharp.text.Image.GetInstance(path + "/logo.png");

            /*
            * scale image to fit available space, if needed
            */
            //  _img.ScalePercent(50);
        }
        public override void OnEndPage(PdfWriter writer, Document document) {
            Rectangle page = document.PageSize;

            headerfooter hfPage = new headerfooter();

            hfPage.setHeader(path, page.Width - 35, Element.ALIGN_RIGHT, Rectangle.NO_BORDER, 100);
            hfPage.setFooter(page.Width);
            PdfPTable head = hfPage.Head;
            PdfPTable foot = hfPage.Foot;


            /*
            * write header w/WriteSelectedRows(); requires absolute positions!
            */
            head.WriteSelectedRows(
               0, -1,          // first/last row; -1 flags all write all rows
               0, // left offset
                // ** bottom** yPos of the table
                // page.Height - document.TopMargin + head.TotalHeight,
              820,
               writer.DirectContent
             );


            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
        }
    }// end of Thao code

    protected void setOilReportTable(string component_id) {
        DataTable oilReport = or.getOilReportByComponentId(component_id);
        DataTable tk = new DataTable();
        tk.Columns.Add("Sample No", typeof(string));
        tk.Columns.Add("Tested Date", typeof(string));
        tk.Columns.Add("Status", typeof(string));
        tk.Columns.Add("Download Link", typeof(string));
        foreach (DataRow r in oilReport.Rows) {
            DataRow tableRow = tk.NewRow();
            tableRow["Sample No"] = r["sample_id"].ToString();
            tableRow["Tested Date"] = r["tested_date"].ToString();

            tableRow["Status"] = r["status"].ToString();

            tableRow["Download Link"] = r["reportlink"].ToString();
            tk.Rows.Add(tableRow);
        }
        Session["TaskTable"] = tk;
        BindData();

    }
    protected string IntToString(string i) {
        string sta = "";
        switch (i) {
            case "1": sta = "Normal"; break;
            case "2": sta = "Abnormal"; break;
            case "3": sta = "Moderate"; break;
            case "4": sta = "Severe"; break;
        }
        return sta;

    }
    protected void TaskGridView_RowDataBound(object sender, GridViewRowEventArgs e) {
        if (e.Row.RowType == DataControlRowType.DataRow) {
            if (!e.Row.Cells[1].ToString().Equals("") && e.Row.Cells[1].ToString() != null) {
                e.Row.Cells[1].Text = e.Row.Cells[1].Text.Substring(0, 10);
            }
            if (e.Row.Cells[3].ToString().Equals("") || e.Row.Cells[3].ToString() == null) {
                e.Row.Cells[3].Text = "N/A";

            } else {
                //  string path = String.Format("{0}\\inbox", Server.MapPath(".."));
                string reportlink2 = "../inbox/" + e.Row.Cells[3].Text;
                // reportlink2 = "../" + dr_sample["reportlink"].ToString();

                e.Row.Cells[3].Text = "<a href='" + reportlink2 + "' target=_blank>Download";
            }


            //int i = e.Row.DataItemIndex;
            //e.Row.Cells[0].ForeColor = Color.Blue;
            //TextBox tb1 = (TextBox)e.Row.FindControl("TextBox1");
            //tb1.Text = ((DataTable)(Session["TaskTable"])).Rows[i]["Attribute"].ToString();

            //// tb1.Text = showData.Rows[i]["Attributes"].ToString();
            //TextBox tb2 = (TextBox)e.Row.FindControl("TextBox2");
            //tb2.Text = ((DataTable)(Session["TaskTable"])).Rows[i]["Value"].ToString();
            //if (tb1.Text == "UIN")
            //{
            //    tb1.ReadOnly = true;
            //    // tb1.Visible = false;
            //    tb2.ReadOnly = true;
            //    // tb2.Visible = false;
            //}


        }
    }
    private void BindData() {
        GridView1.DataSource = Session["TaskTable"];
        GridView1.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {

            component_id = Request.QueryString["component_id"].ToString();
            setOilReportTable(component_id);
            // client = ClientDetails;
            if (ClientDetails != null) {
                int parentClientID = ClientDetails.ParentClientID;
                if (parentClientID == 0) {
                    Clients = report.getClientsByParent(ClientDetails.ClientID);
                    if (Clients.Rows.Count == 0) {
                        Clients.Rows.Add(ClientDetails.ClientName, ClientDetails.ClientID);
                    }
                } else {
                    Clients.Columns.Add("clientName", typeof(string));
                    Clients.Columns.Add("client_id", typeof(int));
                    Clients.Rows.Add(ClientDetails.ClientName, ClientDetails.ClientID);
                    //    selectedClient = ClientDetails.ClientID;
                }
                int ok = 1;
                foreach (DataRow cl in Clients.Rows) {
                    String clientName = cl["clientName"].ToString();
                    String clientid = cl["client_id"].ToString();
                    System.Web.UI.WebControls.ListItem clientitem = new System.Web.UI.WebControls.ListItem(clientName, clientid, true);
                    DropDownClientList.Items.Add(clientitem);
                    if (ok == 1) {
                        DropDownClientList.SelectedValue = clientid;
                        ok = 0;
                        selectedClient_id = ToInt(clientid);
                    }
                }
                // selectedClient = ToInt(DropDownClientList.SelectedValue);
            } else {
                string jscript = "<script language='javascript'  type='text/javascript'> parent.document.location.href= '../Default.aspx'</script>";
                //Page.RegisterClientScriptBlock("key2ClientBlock", jscript);
                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "key3ClientBlock", jscript);

            }

        }


    }
    protected PdfPTable setLegendTable(float width) {
        PdfPTable legendTable = new PdfPTable(2);
        // legendTable.TotalWidth = width+30;
        legendTable.SetTotalWidth(new float[] { 25, 170 });
        legendTable.WidthPercentage = 90;
        DataTable statusTable = new DataTable();
        statusTable = report.getSeverity();
        Phrase title = new Phrase("");
        PdfPCell c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        title = new Phrase("LEGEND", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));
        c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        foreach (DataRow r in statusTable.Rows) {
            string statusName = r["statusName"].ToString();
            string statusDes = r["statusDescription"].ToString();
            int status_id = ToInt(r["status_id"].ToString());
            Phrase p1 = new Phrase(statusName, getFont(getColor(status_id), 8, "Arial"));
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;

            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            legendTable.AddCell(fc);
            p1 = new Phrase(statusDes, getFont(BaseColor.BLACK, 8, "Arial"));
            fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            legendTable.AddCell(fc);
        }

        return legendTable;
    }
    //create table of information for the first page
    protected PdfPTable setTableInfo(ArrayList info, float width) {
        PdfPTable tableInfo = new PdfPTable(2);
        Chunk ck;


        iTextSharp.text.Font font1;
        tableInfo.TotalWidth = width;
        for (int i = 0; i < 16; i++) {
            Phrase p1 = new Phrase();
            switch (i) {
                case 0:
                case 2:
                case 4:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 1:
                case 3:
                case 5:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 11);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 13:
                case 15:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10.5f);
                    String address = info[i].ToString();
                    String t;
                    int index = 0;
                    int count = 0;
                    while (true) {
                        count = address.IndexOf(';', index);
                        if (count == -1) {
                            ck = new Chunk(address.Substring(index).Trim(), font1);
                            p1.Add(ck);
                            break;
                        }
                        t = address.Substring(index, count - index).Trim();
                        index = count + 1;
                        ck = new Chunk(t, font1);
                        p1.Add(ck);
                        p1.Add(Chunk.NEWLINE);

                    }
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 12:
                case 14:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                default:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 9.5f);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
            }
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.MinimumHeight = 0f;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            if ((i > 5) && (i < 10)) {
                // fc.SetLeading(0, 1.0f);
                fc.FixedHeight = 13;

            } else
                fc.MinimumHeight = 0;
            fc.PaddingBottom = 0.1f;
            fc.PaddingTop = 0.1f;
            tableInfo.AddCell(fc);
        }
        return tableInfo;

    }
    protected Font getFont(BaseColor color, float size, string type) {
        Font font = new Font();
        font.Color = color;//BaseColor.BLUE;
        font.Size = size;// 6f;
        font.SetFamily(type);//"Arial");
        return font;
    }
    protected void Severity_changed(object sender, EventArgs e) {
        if (SelectSeverity_DropDownList.SelectedValue == "Choose Severity") {
            if (changeSeverity == false) {
                ReportServices rs = new ReportServices();
                // ds = rs.getOptions(CLIENTID);
                // severity= ds.Tables[0];
                severity = rs.getSeverity();
                changeSeverity = true;
            }
            foreach (DataRow status in severity.Rows) {
                String statusName = status["statusName"].ToString();
                string statusID = status["status_id"].ToString();

                System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(statusName, statusID, true);
                SeverityCheckBoxList.Items.Add(ls);
            }

        } else {
            SeverityCheckBoxList.Items.Clear();
        }



    }
    protected DataTable getSelectedSites() {
        DataTable selectedSites = new DataTable();
        selectedSites.Columns.Add("siteName", typeof(string));
        selectedSites.Columns.Add("site_id", typeof(int));
        if (SelectSite_DropDownList1.SelectedValue == "Choose Sites") {

            foreach (System.Web.UI.WebControls.ListItem lt in SitesCheckBoxList.Items) {

                if (lt.Selected) {
                    string siteName = "";
                    siteName = lt.Text;
                    int siteID = Int32.Parse(lt.Value);
                    selectedSites.Rows.Add(siteName, siteID);
                }
            }
        } else {
            if (changeSite == false) {
                ReportServices rs = new ReportServices();

                Sites = rs.getSiteByCLientID(selectedClient_id);
                changeSite = true;
            }
            selectedSites = Sites;

        }
        return selectedSites;
    }
    protected DataTable getSelectedStatus() {
        DataTable selectedStatus = new DataTable();
        selectedStatus.Columns.Add("statusName", typeof(string));
        selectedStatus.Columns.Add("status_id", typeof(int));
        if (SelectSeverity_DropDownList.SelectedValue == "Choose Severity") {

            foreach (System.Web.UI.WebControls.ListItem lt in SeverityCheckBoxList.Items) {

                if (lt.Selected) {
                    string statusName = "";
                    statusName = lt.Text;
                    int statusID = Int32.Parse(lt.Value);
                    selectedStatus.Rows.Add(statusName, statusID);
                }
            }
        } else {
            if (changeSeverity == false) {
                ReportServices rs = new ReportServices();
                severity = rs.getSeverity();
                changeSeverity = true;
            }
            selectedStatus = severity;

        }
        return selectedStatus;
    }


    protected void Client_Changed(object sender, EventArgs e) {
        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        SelectSite_DropDownList1.Text = "Any";
        SelectSite_DropDownList1.SelectedIndex = 0;
        SitesCheckBoxList.Items.Clear();
        changeSite = false;
    }
    protected string getShortName(string name) {
        string name1 = name.Trim();
        //int length = name.Length;
        string shorname = "";
        int ix = 0;
        shorname = shorname + name.Substring(0, 1).ToString().ToUpper();
        name1 = name.Substring(1);
        int index = index = name1.IndexOf(" ", ix);
        while (index != -1) {

            name1 = name1.Substring(index).Trim();
            shorname = shorname + name1.Substring(0, 1);
            index = name1.IndexOf(" ", ix);
        }
        return shorname;
    }
    protected void Site_changed(object sender, EventArgs e) {
        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        if (SelectSite_DropDownList1.SelectedValue == "Choose Sites") {
            if (changeSite == false) {
                ReportServices rs = new ReportServices();
                Sites = rs.getSiteByCLientID(selectedClient_id);
                changeSite = true;
            }
            foreach (DataRow site in Sites.Rows) {
                String siteName = site["siteName"].ToString();
                string siteID = site["site_id"].ToString();

                System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(siteName, siteID, true);
                SitesCheckBoxList.Items.Add(ls);
            }

        } else {
            SitesCheckBoxList.Items.Clear();
        }



    }
    protected BaseColor getColor(int status_id) {
        switch (status_id) {
            case 1: return BaseColor.GREEN;
            case 2: return BaseColor.YELLOW;
            case 3: return BaseColor.ORANGE;
            case 4: return BaseColor.RED;
            case 5: return BaseColor.BLUE;
            default: return BaseColor.BLACK;
        };


    }
    protected Paragraph getFirstPage() {
        Paragraph pr = new Paragraph();
        //pr.Font=getFont(BaseColor.BLACK,
        pr.Add(new Chunk("Vibration Survey & Report", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 18)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Vibration Monitoring", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Vibration analysis is a predictive maintenance method, which allows for early problem identification in active machines and is the most effective machine condition monitoring technique. Early detection of gear tooth wear, bearing deterioration, shaft misalignment, structural looseness, imbalance, cavitation, and all other correctable problems allows planned adjustment and repairs to equipment. This avoids costly breakdown repairs and disruption to operations. I2i uses latest tri-axial technology to collect data from all three planes simultaneously. This makes our machine assessment reports not only more accurate than our competitors but also allows for faster data acquisition and greater access to your plant and equipment from a single point location.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Survey and Data Collection", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("An i2i engineer will visit your site to carryout a survey and collect data and samples as required at the pre-arranged time. A preliminary analysis report of any significant defects found and course of action will be printed and made available for discussion before the engineer leaves the site.  Site time may vary depending on how long it takes to survey the equipment due to its operational availability including both vehicular and safe plant access", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Analysis and Reporting", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Once collected, the data is analysed by our trained engineers and a preliminary report is generated that identifies any OUT of LIMIT equipment faults and problem rectification while our engineers are still on site.  The data is then transferred to our Brisbane office for further analysis. This includes various techniques such as Narrow Band Alarms, RMS trends; Crest Factor (intensity), Statistical Process Control, Phase Relationship and Demodulation are used in every reading to assist the analysis. ", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("The report lists all the client’s machines (any un-surveyed are still listed, but Machine un-surveyed is entered under that machine). For each machine, the report details any problems found and their severity, as well as any recommended corrective actions.  A full report is then emailed within (3) Three days in PDF format, with a bound hard copy posted out to the client or client’s representative.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Equipment", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("DLI Engineering DCX XRT PC based portable Four Channel data collection unit and analyser, serial number 556; DLI Engineering accelerometer, model N0 9938-7-NC-DLI serial number S/N 1223", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("General Layout of each page", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        Chunk chunk = new Chunk("A numbered list of equipment is generally shown on each page. The “equipment”, “component” and “criticality level” is detailed and colour coded next to each component surveyed. The headings can include descriptions requested by the client, or in the absence of this a convenient designation is made by the analyst.  A reference filename is also given for the report stored on the i2i computer system for future reference if required.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10));
        pr.Add(chunk);
        pr.Alignment = Element.ALIGN_JUSTIFIED;
        pr.SpacingAfter = 0;
        pr.SpacingBefore = 0;
        pr.Leading = 13;
        return pr;

    }
    protected void MergeFiles(string file1, string file2) {

        try {

            int f = 0;

            // we create a reader for a certain document

            PdfReader reader = new PdfReader(file2);

            // we retrieve the total number of pages

            int n = reader.NumberOfPages;

            //Console.WriteLine("There are " + n + " pages in the original file.");

            // step 1: creation of a document-object

            Document document = new Document(reader.GetPageSizeWithRotation(1));

            // step 2: we create a writer that listens to the document

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(file1, FileMode.Create));

            // step 3: we open the document

            document.Open();

            PdfContentByte cb = writer.DirectContent;

            PdfImportedPage page;

            int rotation;

            // step 4: we add content

            while (f < file2.Length) {

                int i = 0;

                while (i < n) {

                    i++;

                    document.SetPageSize(reader.GetPageSizeWithRotation(i));

                    document.NewPage();

                    page = writer.GetImportedPage(reader, i);

                    rotation = reader.GetPageRotation(i);

                    if (rotation == 90 || rotation == 270) {

                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);

                    } else {

                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);

                    }

                    //Console.WriteLine("Processed page " + i);

                }

                f++;

                if (f < file2.Length) {

                    reader = new PdfReader(file2);

                    // we retrieve the total number of pages

                    n = reader.NumberOfPages;

                    //Console.WriteLine("There are " + n + " pages in the original file.");

                }

            }

            // step 5: we close the document

            document.Close();

        } catch (Exception e) {

            string strOb = e.Message;

        }

    }
    protected string getSitesTitle(DataTable sites) {
        string sitesTitle = "";
        int num = sites.Rows.Count;
        int i = 0;

        foreach (DataRow s in sites.Rows) {
            sitesTitle = sitesTitle + s["siteName"].ToString();
            i++;
            if (i + 1 == num)
                sitesTitle = sitesTitle + " & ";
            else

                if (i != num)
                    sitesTitle = sitesTitle + ", ";

        }
        return sitesTitle;
    }
    protected PdfPTable setTitleTable(ArrayList title, float width) {
        PdfPTable titleTable = new PdfPTable(1);
        //titleTable.SetTotalWidth(new float[] {5 });
        titleTable.WidthPercentage = 82;

        Chunk ck;


        Font font1; Phrase p1 = new Phrase();
        // titleTable.TotalWidth = width-80;
        for (int i = 0; i < title.Count; i++) {
            if (i + 1 == title.Count)
                font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 13);
            else
                font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 15);
            ck = new Chunk(title[i].ToString(), font1);


            p1.Add(ck);
            p1.Add(Chunk.NEWLINE);
            p1.Add(Chunk.NEWLINE);
        }
        PdfPCell fc = new PdfPCell(p1);
        fc.HorizontalAlignment = Element.ALIGN_CENTER;
        fc.VerticalAlignment = Element.ALIGN_MIDDLE;
        fc.MinimumHeight = 0f;
        fc.Border = Rectangle.NO_BORDER;
        fc.VerticalAlignment = Element.ALIGN_LEFT;
        fc.MinimumHeight = 0;
        fc.PaddingBottom = 0.1f;
        fc.PaddingTop = 0.1f;
        //fc.Leading=15f;
        titleTable.AddCell(fc);


        return titleTable;
    }
    string testing(DataTable sites, DataTable Status, string date) {
        string query = "";
        string machineList = "";
        string statusList = "";
        bool first = true;
        foreach (DataRow r in sites.Rows) {
            string machine_id = r["site_id"].ToString();
            if (first == true) {
                machineList = machineList + "(" + machine_id;
                first = false;
            } else
                machineList = machineList + "," + machine_id;
        }
        machineList = machineList + ")";
        first = true;
        foreach (DataRow r in Status.Rows) {
            string status_id = r["status_id"].ToString();
            if (first == true) {
                statusList = statusList + "(" + status_id;
                first = false;
            } else {
                statusList = statusList + "," + status_id;
            }
        }
        statusList = statusList + ")";

        query = query + " SELECT        o.reportlink, o.status, c.componentName, c.component_id, m.site_id,m.machineName" +
                       " FROM       OilReports AS o INNER JOIN" +
                                  " Components AS c ON o.Component_id = c.component_id INNER JOIN" +
                                  " Machines AS m ON c.machine_id = m.machine_id" +
                       " WHERE     (m.site_id IN " + machineList + ") AND (o.status IN  (SELECT        statusName AS sn " +
                       "  FROM            Status WHERE        (status_id IN  " +
                        statusList + "))) AND (convert(varchar(10),o.tested_date,3) = '" + date + "')";
        return query;

    }
    protected void FullReport(object sender, EventArgs e) {
        System.DateTime str_date = new System.DateTime();
        string selectedDate = "";
        Document document = new Document(PageSize.A4, 120, 85, 83, 125);
        headerfooter hf = new headerfooter();
        UserServices us = new UserServices();
        DataTable selectedSites = new DataTable();
        DataTable selectedStatus = new DataTable();
        selectedSites.Columns.Add("siteName", typeof(string));
        selectedSites.Columns.Add("site_id", typeof(int));
        selectedStatus.Columns.Add("statusName", typeof(string));
        selectedStatus.Columns.Add("status_id", typeof(int));


        string ClientParentName = "";

        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        int dateIndex = 0;
        selectedClient = us.getClientByID(selectedClient_id);

        string selectedClientName = selectedClient.ClientName;

        try {
            // selectedDate = DropDownListDate.SelectedValue.Substring(0, DropDownListDate.SelectedValue.IndexOf(" ")).Trim();
            //str_date = DateTime.Parse(selectedDate, System.Globalization.CultureInfo.CreateSpecificCulture("en-AU").DateTimeFormat);
            selectedDate = DropDownListDate.SelectedValue;
            dateIndex = DropDownListDate.SelectedIndex + 1;//Request.QueryString["selectedDate"].ToString();

        } catch (Exception ex) {
            Console.Write(ex);
            // MessageBox.Show("No report available");

        }
        // step 2: we create a writer that listens to the document
        String path1 = Server.MapPath("Report");
        String p = Server.MapPath("Images");

        String path = path1 + "/Template.pdf";


        int ok = 0;
        while (ok != -1) {

            try {

                writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
                ok = -1;
            } catch (Exception) {
                ok++;
                path = path1 + "/Template" + ok.ToString() + ".pdf";
            }
        }


        Rectangle page = document.PageSize;
        // document.SetMargins(120, 90, 83, 30);
        document.SetMargins(120, 20, 83, 125);

        hf.setHeader(p + "/logoi2i.png", page.Width + 35, Element.ALIGN_CENTER, Rectangle.NO_BORDER, 75);
        hf.setFooter(page.Width);

        PdfPTable head = hf.Head;
        PdfPTable foot = hf.Foot;

        try {

            selectedSites = getSelectedSites();

            selectedStatus = getSelectedStatus();
            document.Open();

            // Add header for first page
            head.WriteSelectedRows(0, -1, 0, 820, writer.DirectContent);
            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
            if (ClientDetails.ParentClientID != 0) {
                ClientParentName = "" + us.getClientByID(ClientDetails.ParentClientID).ClientName;
            } else
                ClientParentName = ClientDetails.ClientName;


            title.Add(ClientParentName + " (" + selectedClientName + ")"); // + " Sites";

            string sitesTitle = getSitesTitle(selectedSites);

            title.Add(sitesTitle);
            title.Add("Oil Inspection and Survey Report");
            title.Add(selectedDate);
            PdfPTable TitleTable = new PdfPTable(1);
            TitleTable = setTitleTable(title, page.Width);


            for (int i = 0; i < 2; i++) {
                Phrase t = new Phrase("");
                pa = new Paragraph(t);
                if (i == 0)
                    pa.Leading = 110;
                else
                    pa.Leading = 20;
                pa.Alignment = Element.ALIGN_CENTER;
                document.Add(pa);


            }
            TitleTable.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(TitleTable);
            string fileName = "" + selectedClient.ClientID + "-VA-" + getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";
            PdfPTable information = new PdfPTable(2);
            infor.Add("Engineer");
            infor.Add("Paul Clibbon");
            infor.Add("Report Filename");
            infor.Add(fileName);
            infor.Add("Report Distribution");
            infor.Add(selectedClient.ContactPerson);
            infor.Add("Phone");
            infor.Add(selectedClient.PhoneMobile.ToString());
            infor.Add("Fax");
            infor.Add(selectedClient.Fax.ToString());
            infor.Add("Email");
            infor.Add(selectedClient.Email);
            infor.Add("Address");
            infor.Add(selectedClient.Address);
            infor.Add("Report Distribution: Email reports in PDF format to:  ");
            infor.Add(selectedClient.DistributedEmail);
            information = setTableInfo(infor, page.Width - 80);
            information.HorizontalAlignment = Element.ALIGN_CENTER;
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(information);
            /* PdfPTable legend = new PdfPTable(2);
             legend = setLegendTable(page.Width);
             legend.HorizontalAlignment = Element.ALIGN_LEFT;
             document.Add(legend);           */



            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            // document.Add(information);
            PdfPTable legend = new PdfPTable(2);
            legend = setLegendTable(page.Width);
            legend.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(legend);

            // add new page
            document.SetMargins(120, 76, 83, 125);
            document.NewPage();



            document.NewPage();

            // set event automatically generate header for all next pages
            _events ev = new _events(p);
            writer.PageEvent = ev;



            DataTable MachinesOfSites = new DataTable();
            ReportServices r = new ReportServices();
            // MachinesOfSites = r.getMachineOfSites(selectedSites);
            DataTable componentsOfSites = new DataTable();

            //string test = testing(selectedSites, selectedStatus, selectedDate);
            //TextBox1.Text = test;
            // componentsOfSites = or.getComponentsByMachinesAndStatusByDate(MachinesOfSites, selectedStatus,selectedDate);
            componentsOfSites = or.getComponentsBySitesAndStatusByDate(selectedSites, selectedStatus, selectedDate);// str_date);

            int num = componentsOfSites.Rows.Count;

            int index = 0;
            // int listCount = 1;
            int sourseIndex = 0;
            string oilPath = path1.Replace("\\client\\Report", "") + "\\inbox\\";


            sourses.Add(path);
            string lk = "";
            foreach (DataRow site in selectedSites.Rows) {
                String siteName = site["siteName"].ToString();
                string siteID = site["site_id"].ToString();
                //bool haveValue = false;
                // Phrase content = new Phrase(siteName,getFont(BaseColor.BLACK, 16f, "Arial"));
                // Paragraph contentPa = new Paragraph(content);
                // contentPa.Leading = 10;
                //// contentPa.Font = 
                // contentPa.Alignment = Element.ALIGN_CENTER;
                // document.Add(contentPa);

                index++;
                //int count = 0;
                DataRow[] componentsOfSite = componentsOfSites.Select("site_id =  " + siteID.Trim());
                //if (componentsOfSite.Length == 0)
                //{
                //    string noValue = " No component met the search criteria!";
                //    content = new Phrase(noValue, getFont(BaseColor.BLACK, 12f, "Arial"));
                //    contentPa = new Paragraph(content);
                //    document.Add(Chunk.NEWLINE);
                //    document.Add(Chunk.NEWLINE);
                //    document.Add(Chunk.NEWLINE);
                //    document.Add(contentPa);
                //    document.NewPage();
                //    continue;
                //}
                lk = lk + "site: " + siteID;
                foreach (DataRow co in componentsOfSite) {
                    string nameLink = co["reportlink"].ToString();

                    string sourse = oilPath + nameLink;
                    lk = lk + ";" + sourse;

                    //sourses[sourseIndex] = sourse;
                    sourses.Add(sourse);


                    sourseIndex++;
                }


                document.NewPage();

            }
            document.Close();
            TextBox1.Text = "" + num + ";lk:" + lk;
            PdfMerge merg = new PdfMerge();

            string file = merg.MergeFiles(oilPath, sourses);



            // set name for attact file


            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/pdf";
            //Response.WriteFile(path);
            Response.WriteFile(file);
            Response.Flush();
            Response.End();
            Response.Clear();

        } catch (Exception ee) {
            Console.Error.WriteLine(ee.StackTrace);
            Console.Error.WriteLine(ee.Message);

            if (ee.InnerException != ee) {

                // Console.Error.WriteLine(ee.InnerException.Message);
            }
        }



        // End of Thao



    }
}
